package com.sentiwt.classifier;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sentiwt.dao.NoiseWordDAO;
import com.sentiwt.dao.WordDAO;
import com.sentiwt.jpa.Sentiment;

@Controller
public class SentimentClassifier {
	
	@Autowired
    private NoiseWordDAO noiseWordDao;
	
	@Autowired
    private WordDAO wordDao;
	
	private final String PUNCTUATION ="`~!@#$%^&*()_-=+|\\][}{';\":?></.,"; //32

	@RequestMapping(value="/classify")
    public ModelAndView classify(HttpServletRequest request) {
		 String statement = request.getParameter("statement");
		 Sentiment sent = classify(statement);
		 Map modelMap = new ModelMap();
		 modelMap.put("sentiment", sent.name());
		 return new ModelAndView("classify.jsp", modelMap);
		
	}
	
	public Sentiment classify(String sampleStatement) {
		//remove punctuation and split
		String[] words = removePunctuation(sampleStatement).split(" ");
		
		//TODO remove noise words
//		System.out.println(noiseWordDao.toString());
		String[] keywords = ignoreNoiseWords(words);
		
		//TODO sentiment analysis
		return Sentiment.HAPPY;
	}
	
	private String removePunctuation(String sentence) {
		String sentenceWoPunctuation = "";
		int punctuationLength = this.PUNCTUATION.length();
		int start = 0;
		for(int i=0; i<punctuationLength; i++) {
			int index = sentence.indexOf(this.PUNCTUATION.charAt(i));
			if(index != -1) {
//				System.out.println(index + " punct: "+this.PUNCTUATION.charAt(i));
				sentenceWoPunctuation += sentence.substring(start, index);
				start = index+1;
			}
		}
		return sentenceWoPunctuation;
	}
	
	private String[] ignoreNoiseWords(String[] words) {
		List<String> keyWords = new ArrayList<String>();
		
		for(String word : words) {
			if(!noiseWordDao.isNoiseWord(word)) {
				keyWords.add(word);
			}
		}
		
		String[] wordsArray = new String[keyWords.size()];
		keyWords.toArray(wordsArray);
		return wordsArray;
	}
	
	
}
